package com.yunhe.rentcars.pro.aspect;

import com.yunhe.rentcars.commons.annoaction.Log;
import com.yunhe.rentcars.pro.constant.Constant;
import com.yunhe.rentcars.pro.dao.system.SysLogDao;
import com.yunhe.rentcars.pro.entity.permi.User;
import com.yunhe.rentcars.pro.entity.system.SysLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import java.util.Date;
@Aspect
@Component
public class SysLogAspect {
    private static Logger logger = LoggerFactory.getLogger(SysLogAspect.class);  //日志记录
    @Autowired
    private SysLogDao sysLogDao;


    //配置controller环绕通知,使用在方法aspect()上注册的切入点
    @Around("execution(* com.yunhe.rentcars.pro.service..impl.*.*(..)) && @annotation(log)")
    public void around(ProceedingJoinPoint joinPoint,Log log)  {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //从sesson中获取当前登录对象
        User user = (User)request.getSession().getAttribute(Constant.SK_USER);
        int type = log.type();  //操作类型
        String value = log.value();  //操作描述

        //Object[] args = joinPoint.getArgs();
        //String argsJson = JSON.toJSONString(args);  //将得到参数的JSON串

        SysLog systLog = new SysLog("admin",value,type,new Date());
        //SysLog systLog = new SysLog(user.getUsername(),value,type,new Date()); //后面做登录以后修改为当前登录用的的名字
        try {
            joinPoint.proceed();  //执行目标方法
            //获取request
            systLog.setSuccess(true);  //执行成功

        } catch (Throwable throwable) {
            systLog.setSuccess(false);
            throw new RuntimeException(throwable);
        }finally {
            sysLogDao.save(systLog);
        }
    }
}

